package com.example.myproject.shardjdbc.tablestrategy;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * id 精准算法
 *
 * @author yangbin
 * @date 2020年05月11日
 */
public class IdShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> {

    private Logger log = LoggerFactory.getLogger(PreciseShardingAlgorithm.class);

    public String doSharding(final Collection<String> tableNames, final PreciseShardingValue<Long> shardingValue) {
        StringBuilder sb = new StringBuilder();
        Long shardValue = shardingValue.getValue();
        //获取设置的虚拟表名称，这里获取到的logicTableName=jf_company_freeze_record
        String logicTableName = shardingValue.getLogicTableName();
        sb.append(logicTableName).append(shardValue%3);
        if (tableNames.contains(sb.toString())) {
            return sb.toString();
        } else {
            log.info("取模精确分片策略：没找到与分片键匹配的表名! {} : {} = {}", shardingValue.getLogicTableName(), shardingValue.getColumnName(), shardingValue.getValue());
            throw new UnsupportedOperationException();
        }
    }
}